package com.zhengtoudai.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zhengtoudai.injector.PerActivity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 数据库管理类
 */
@PerActivity
public class DBManager {
    private DBHelper mHelper;
    private SQLiteDatabase db;
    private String TABLE_NAME="user";//数据库表名

    @Inject
    public DBManager(Context context) {
        mHelper = new DBHelper(context);
        //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);
        //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
        db = mHelper.getWritableDatabase();
    }

    /**
     * 添加用户集合
     * @param userInfos
     */
    public void add(List<UserInfo> userInfos) {
        db.beginTransaction();//开启事务
        try {
            for (UserInfo userInfo : userInfos) {
                db.execSQL("INSERT INFO "+TABLE_NAME+" VALUES(null,?,?)", new Object[]{userInfo.getPhone(), userInfo.getPassword()});
            }
            db.setTransactionSuccessful(); //设置事务成功完成
        }finally {
            db.endTransaction();//结束事务
        }
    }

    /**
     * 添加单个用户
     * @param info
     */
    public void add(UserInfo info){
        UserInfo userInfo=query(info.getPhone());//查询当前手机号是否存在
        if (userInfo!=null){ //如果存在
            if (!userInfo.getPassword().equals(info.getPassword())){ //但是密码不一样
                updatePassword(info);//就修改该用户密码
            }
            // /否则就是 手机密码都一样，不存。
                return;
        }
        db.beginTransaction();//开启事务
        try {
            db.execSQL("INSERT INTO "+TABLE_NAME+" VALUES(null,?,?)", new Object[]{info.getPhone(), info.getPassword()});
            db.setTransactionSuccessful(); //设置事务成功完成
        }finally {
            db.endTransaction();//结束事务
        }
    }

    /**
     * 修改密码
     * @param info
     */
    public void updatePassword(UserInfo info){
        ContentValues cv=new ContentValues();
        cv.put("password",info.getPassword());
        db.update(TABLE_NAME,cv,"phone=?",new String[]{info.getPhone()});
    }

    /**
     * 删除传入的用户
     * @param phone
     */
    public boolean deleteUser(String phone){
        int result=db.delete(TABLE_NAME,"phone=?",new String[]{phone});
        return result==0?true:false;
    }

    /**
     * 查询所有用户
     * @return
     */
    public List<UserInfo> queryAll(){
        ArrayList<UserInfo> userInfos=new ArrayList<>();
        Cursor cursor=queryTheCursor();
        while (cursor.moveToNext()){
            UserInfo userInfo=new UserInfo();
            userInfo.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
            userInfo.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            userInfo.setPassword(cursor.getString(cursor.getColumnIndex("password")));
            userInfos.add(userInfo);
        }
        cursor.close();
        return userInfos;
    }

    /**
     * 根据手机号查询单个用户
     * @param phone
     * @return
     */
    public UserInfo query(String phone){
        if(phone==null||phone.equals("")){
            return null;
        }
        Cursor cursor=queryTheCursor();
        while (cursor.moveToNext()){
            if (phone.equals(cursor.getString(cursor.getColumnIndex("phone")))){
                UserInfo userInfo=new UserInfo();
                userInfo.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
                userInfo.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
                userInfo.setPassword(cursor.getString(cursor.getColumnIndex("password")));
                return userInfo;
            }
        }
        return null;
    }
    /**
     * 获取当前数据库游标
     * @return
     */
    public Cursor queryTheCursor(){
        return db.rawQuery("SELECT * FROM "+TABLE_NAME,null);
    }

    /**
     * 关闭数据库
     */
    public void closeDB() {
        db.close();
    }
}
